from django.core.management.base import BaseCommand, CommandError
from optparse import make_option

from django.conf import settings
from django.db import connection, models
from time import strftime
import time

from djfacet.constants import *
from djfacet.facetviews import *
from djfacet.fb_utils.utils import djfacetlog


##################
#  Tue Sep 14 15:29:58 CEST 2010
#	
#
##################



# EG:
# bash-3.2$ python manage.py djfacet_createcache
# bash-3.2$ python manage.py djfacet_createcache gender
# bash-3.2$ python manage.py djfacet_createcache gender --secondlevel=yes  --lowerlimit=9905
# bash-3.2$ python manage.py djfacet_createcache possoffice possunfreepersons posslands possrevkind possrevsilver privileges

class Command(BaseCommand):
	args = '<facet_uniquename1, facet_uniquename2, facet_uniquename3 etc. >'
	help = 'Cached all facet values within the facets available'

	# make_option requires options in optparse format
	option_list = BaseCommand.option_list  + (
						make_option('--resulttypes', action='store', dest='resulttypes', default='all',
									help='The _resulttypes_ option determines what resulttypes-facet couple will be cached'),
						make_option('--enforce', action='store', dest='enforce', default='yes',
									help='The _enforce_ option determines whether we delete previously cached object (default= TRUE!)'),
						make_option('--onlyrescounts', action='store', dest='onlyrescounts', default='no',
									help='The _onlyrescounts_ option determines whether to update only the res tot-counts (no facet values)'),

				  )


	# :an init method that does the repetitive stuff....
	def __init__(self, *args, **kwargs):
		
		loaded_facet_groups = []
		facets_for_template = []

		# load facet specs 
		# 1: create groups from SPECS.facet_groups	
		for x in reversed(sorted(DJ_SPECS.facet_groups, key=lambda (k): k['position'])):
			if x['default']:
				loaded_facet_groups.append(FacetsGroup(x['uniquename'], x['label'], x['position'])) 
				
		# 2: load facets into groups using SPECS.facetslist				
		for g in loaded_facet_groups:
			g.buildfacets_fromspecs(DJ_SPECS.facetslist)
		
		# 3: load result types
		self.result_types = DJ_SPECS.result_types 

		# initialize the faceted manager
		self.fm = FacetedManager(loaded_facet_groups, self.result_types)
		self.fm.init_resulttypes_activeIDs()	 #cache this in memory first.
		
		super(Command, self).__init__(*args, **kwargs)



	def handle(self, *args, **options): 
		"""
		args - args (eg. myapp in "manage.py reset myapp") = the facet names [result types ...]
		options - configurable command line options
		"""

		all_facets = self.fm.get_all_facets()
		all_resulttypes = self.result_types
				


		if options['enforce'] == 'yes':
			ENFORCE = True
		else:
			ENFORCE = True  # to be implemented..
			
		if args:
			temp = []
			for a in args:
				djfacetlog("Argument provided: ==%s==" % str(a), True)
				temp += [x for x in all_facets if x.uniquename == str(a)]
			all_facets = temp


		if options['resulttypes'] != 'all':
			test = self.fm.get_resulttype_from_name(options['resulttypes'])
			if test:
				all_resulttypes = [test]


		# feedback:
		print "\n\n++ = ++ = ++ = ++ = ++ = ++ = ++ = ++\n%s\nSTARTING CACHING FACET VALUES WITH PARAMS:"  % strftime("%Y-%m-%d %H:%M:%S")	
		print "facets: " + str([facet.uniquename for facet in all_facets])
		print "resulttypes:  "  + str([resulttype['uniquename'] for resulttype in all_resulttypes])
		print "enforce:  "  + str(options['enforce'])
		print "++ = ++ = ++ = ++ = ++ = ++ = ++ = ++\n"




		#  now do the actions: 


		cacheDB = DbCache(self.fm)

		# 1) cache the result types count  (later we'll have to make this an option for the command...)
		if True:
			cacheDB.cacheResultTypes()
					
		# 2) cache all the values
		if options['onlyrescounts'] == 'no':
			for facet in all_facets:
				for r in all_resulttypes:
					print "\n starting caching at [%s] ...... [facet=%s]"	 %	(strftime("%Y-%m-%d %H:%M:%S"), str(facet.uniquename))
					v = cacheDB._cacheOneFacetValue(facet, resulttype=r, ENFORCE=ENFORCE) 
					if v:
						print "\n[%s]\nzzzzzzzzzzzzzzzzzz sleeping 1 second zzzzzzzzzzzzzzzzzzzzzzzz\n\n"	% strftime("%Y-%m-%d %H:%M:%S")
						time.sleep(1)
					

						
			print '\nSuccessfully cached facets [%s]' % (str([facet.uniquename for facet in all_facets]))
			#  let's clean the cache for unused elements...
			print "\nNow emptying unused elements....."
			print "....DONE: tot emptied elements= %d"	% cacheDB._emptyUnusedElements()


